import 'package:flutter/material.dart';

import 'controller.dart';

/// Signature for when a tap has occurred.
typedef OnItemTap<T> = void Function(T value);

/// Dropdown header widget.
class DropDownHeader extends StatefulWidget {
  final Color color;
  final double borderWidth;
  final Color borderColor;
  final TextStyle style;
  final TextStyle? dropDownStyle;
  final double iconSize;
  final Color iconColor;
  final Color? iconDropDownColor;

//  final List<String> menuStrings;
  final double height;
  final double dividerHeight;
  final Color dividerColor;
  final DropdownMenuController controller;
  final OnItemTap? onItemTap;
  final List<DropDownHeaderItem> items;

  final GlobalKey stackKey;

  /// Creates a dropdown header widget, Contains more than one header items.
  const DropDownHeader({
    Key? key,
    required this.items,
    required this.controller,
    required this.stackKey,
    this.style = const TextStyle(color: Color(0xFF666666), fontSize: 13),
    this.dropDownStyle,
    this.height = 40,
    this.iconColor = const Color(0xFFafada7),
    this.iconDropDownColor,
    this.iconSize = 20,
    this.borderWidth = 1,
    this.borderColor = const Color(0xFFf2f2f2),
    this.dividerHeight = 20,
    this.dividerColor = const Color(0xFFf2f2f2),
    this.onItemTap,
    this.color = Colors.white,
  }) : super(key: key);

  @override
  _DropDownHeaderState createState() => _DropDownHeaderState();
}

class _DropDownHeaderState extends State<DropDownHeader>
    with SingleTickerProviderStateMixin {
  bool _isShowDropDownItemWidget = false;
  late double _screenWidth;
  late int _menuCount;
  final GlobalKey _keyDropDownHeader = GlobalKey();
  TextStyle? _dropDownStyle;
  Color? _iconDropDownColor;

  @override
  void initState() {
    super.initState();
    widget.controller.addListener(_onController);
  }

  _onController() {
    if (mounted) {
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    _dropDownStyle = widget.dropDownStyle ??
        TextStyle(color: Theme.of(context).primaryColor, fontSize: 13);
    _iconDropDownColor =
        widget.iconDropDownColor ?? Theme.of(context).primaryColor;

    MediaQueryData mediaQuery = MediaQuery.of(context);
    _screenWidth = mediaQuery.size.width;
    _menuCount = widget.items.length;

    var gridView = GridView.count(
      physics: const NeverScrollableScrollPhysics(),
      crossAxisCount: _menuCount,
      childAspectRatio: (_screenWidth / _menuCount) / widget.height,
      children: widget.items.map<Widget>((item) {
        return _menu(item);
      }).toList(),
    );

    return Container(
      key: _keyDropDownHeader,
      height: widget.height,
//      padding: EdgeInsets.only(top: 1, bottom: 1),
      decoration: widget.borderWidth == 0
          ? null
          : BoxDecoration(
              border: Border.all(
                color: widget.borderColor,
                width: widget.borderWidth,
              ),
            ),
      child: gridView,
    );
  }

  @override
  dispose() {
    super.dispose();
  }

  _menu(DropDownHeaderItem item) {
    int index = widget.items.indexOf(item);
    int menuIndex = widget.controller.menuIndex;
    _isShowDropDownItemWidget = index == menuIndex && widget.controller.isShow;
    List<Widget> rows = [
      Flexible(
        child: Text(
          item.title,
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: _isShowDropDownItemWidget
              ? _dropDownStyle
              : widget.style.merge(item.style),
        ),
      ),
      Icon(
        !_isShowDropDownItemWidget
            ? item.iconData ?? Icons.arrow_drop_down
            : item.iconDropDownData ?? item.iconData ?? Icons.arrow_drop_up,
        color: _isShowDropDownItemWidget
            ? _iconDropDownColor
            : item.style?.color ?? widget.iconColor,
        size: item.iconSize ?? widget.iconSize,
      ),
    ];
    if (item.num > 0) {
      rows.add(Container(
        width: 5,
      ));
    }
    return InkWell(
      onTap: () {
        final RenderBox? overlay =
            widget.stackKey.currentContext!.findRenderObject() as RenderBox?;

        final RenderBox dropDownItemRenderBox =
            _keyDropDownHeader.currentContext!.findRenderObject() as RenderBox;

        var position =
            dropDownItemRenderBox.localToGlobal(Offset.zero, ancestor: overlay);
//        print("POSITION : $position ");
        var size = dropDownItemRenderBox.size;
//        print("SIZE : $size");

        widget.controller.dropDownMenuTop = size.height + position.dy;

        if (index == menuIndex) {
          if (widget.controller.isShow) {
            widget.controller.hide();
          } else {
            widget.controller.show(index);
          }
        } else {
          if (widget.controller.isShow) {
            widget.controller.hide(isShowHideAnimation: false);
          }
          widget.controller.show(index);
        }

        if (widget.onItemTap != null) {
          widget.onItemTap!(index);
        }

        setState(() {});
      },
      child: Container(
        color: widget.color,
        child: Row(
          mainAxisAlignment: item.mainAxisAlignment,
          children: <Widget>[
            Expanded(
              child: Padding(
                padding: const EdgeInsets.only(left: 15, right: 15),
                child: Stack(
                  alignment: Alignment.topRight,
                  children: [
                    Row(
                      mainAxisAlignment: item.mainAxisAlignment,
                      children: rows,
                    ),
                    Visibility(
                      visible: item.num > 0,
                      child: Positioned(
                        right: 0,
                        top: 8,
                        child: Container(
                          constraints: const BoxConstraints(
                            minHeight: 8,
                            minWidth: 13,
                          ),
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              color: const Color(0xffcccccc),
                              borderRadius: BorderRadius.circular(50)),
                          child: Text(
                            item.num.toString(),
                            textAlign: TextAlign.center,
                            style: const TextStyle(
                              fontSize: 9,
                              color: Colors.white,
                            ),
                          ),
                        ),
                      ),
                    )
                  ],
                ),
              ),
            ),
            index == widget.items.length - 1
                ? Container()
                : Container(
                    height: widget.dividerHeight,
                    decoration: BoxDecoration(
                      border: Border(
                        right: BorderSide(color: widget.dividerColor, width: 1),
                      ),
                    ),
                  ),
          ],
        ),
      ),
    );
  }
}

class DropDownHeaderItem {
  final String title;
  final IconData? iconData;
  final IconData? iconDropDownData;
  final double? iconSize;
  final TextStyle? style;
  final int num;
  final MainAxisAlignment mainAxisAlignment;

  DropDownHeaderItem(
    this.title, {
    this.iconData,
    this.iconDropDownData,
    this.iconSize,
    this.mainAxisAlignment = MainAxisAlignment.center,
    this.style,
    this.num = 0,
  });
}
